package com.pinyoumei.app.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.adapter.RegisterDialogAdapter;
import com.pinyoumei.app.bean.AccountBean;
import com.pinyoumei.app.bean.CodeBean;
import com.pinyoumei.app.bean.NoCodeBean;
import com.pinyoumei.app.bean.RegisterBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.AppManager;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.StatusBarUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.BaseDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.HashMap;
import java.util.Map;

import io.realm.Realm;

/**
 * Created by Administrator on 2021-08-06.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2021-08-06        Administrator             新增Person类
 * 2021-08-06        Administrator             增加sex属性
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private TimeCount timeCount;
    private TextView tv_code;
    private EditText et_phone;
    private EditText et_code;
    private EditText et_code2;
    private EditText et_password;
    private Button bt_register;
    private ImageView iv_eye;
    private boolean is_open_eye = false;
    private Gson gson;
    protected AppManager appManager = AppManager.getInstance();
    private LoadingDailog loadingDailog;
    private String open_id = "";
    private String user_nick_name = "";
    private String user_head_img = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtils.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明
        StatusBarUtils.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtils.setStatusBarDarkTheme(this, true)){
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtils.setStatusBarColor(this,0x55000000);
        }
        // 添加activity 到栈
        appManager.addActivity(this);

        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(this)
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();

        setContentView(R.layout.activity_register);

        if (getIntent().getStringExtra("open_id")!=null){
            open_id = getIntent().getStringExtra("open_id");
            user_nick_name = getIntent().getStringExtra("user_nick_name");
            user_head_img = getIntent().getStringExtra("user_head_img");
        }


        InitWidget();

    }



    private void InitWidget() {

        ImageView iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        bt_register = findViewById(R.id.bt_register);
        bt_register.setOnClickListener(this);


        TextView tv_rule = findViewById(R.id.tv_rule);
        tv_rule.setOnClickListener(this);
        tv_rule.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
        tv_code = findViewById(R.id.tv_code);
        RelativeLayout rl_code = findViewById(R.id.rl_code);
        rl_code.setOnClickListener(this);

        RelativeLayout rl_code2 = findViewById(R.id.rl_code2);
        rl_code2.setOnClickListener(this);
        RelativeLayout rl_eye = findViewById(R.id.rl_eye);
        rl_eye.setOnClickListener(this);
        iv_eye = findViewById(R.id.iv_eye);




        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);
        et_code2 = findViewById(R.id.et_code2);
        et_password = findViewById(R.id.et_password);

        TextChange textChange=new TextChange();
        et_phone.addTextChangedListener(textChange);
        et_code.addTextChangedListener(textChange);
        et_code2.addTextChangedListener(textChange);
        et_password.addTextChangedListener(textChange);

    }


    //EditText的监听器
    class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(et_phone.length()>0&&
                    et_code.length()>0&&
                    et_code2.length()>0&&
                    et_password.length()>0){
                bt_register.setBackground(ContextCompat.getDrawable(RegisterActivity.this,R.drawable.shanpe_green_5dp));

            }else{
                bt_register.setBackground(ContextCompat.getDrawable(RegisterActivity.this,R.drawable.shanpe_gray_green_5dp));


            }
        }
    }
    //定时器类
    class TimeCount extends CountDownTimer {
        //构造方法
        public TimeCount(long millisInFuture, long countDownInterval){
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished){
            tv_code.setTextColor(ContextCompat.getColor(RegisterActivity.this,R.color.gray_text_color));
            SpannableString spannableString = new SpannableString((millisUntilFinished/1000)+"秒后重新获取");
            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.GREEN);
            spannableString.setSpan(foregroundColorSpan, 0, 3, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            tv_code.setText(spannableString);

        }
        @Override
        public void onFinish(){
            tv_code.setText("重新获取");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;


            case R.id.bt_login:
                startActivity(new Intent(RegisterActivity.this, AccountLoginActivity.class));
                break;


            case R.id.tv_rule:
                Intent intent = new Intent(RegisterActivity.this, WebViewActivity.class);
                intent.putExtra("order_title", "");
                intent.putExtra("url",Constants.MAIN_URL + "h5/protocol");
                startActivity(intent);
                break;

            case R.id.rl_eye:
                if (is_open_eye){
                    is_open_eye = false;
                    iv_eye.setImageResource(R.mipmap.ic_close_eye);
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }else{
                    is_open_eye = true;
                    iv_eye.setImageResource(R.mipmap.ic_open_eye);
                    et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                break;

            case R.id.rl_code:
                //验证码

                String phones = et_phone.getText().toString().trim();
                if (!TextUtils.isEmpty(phones)){
                    SendCode(phones,1);



                }else{
                    ToastUtils.showShort("请输入手机号");
                }

                break;

            case R.id.rl_code2:
                    Have_No_Code();


                break;

            case R.id.bt_register:
                String phone = et_phone.getText().toString().trim();
                String code = et_code.getText().toString().trim();
                String code2 = et_code2.getText().toString().trim();
                String password = et_password.getText().toString().trim();

                if(!TextUtils.isEmpty(phone)){
                    String rePhone = phone.replace(" ","");
                    if(rePhone.length() != 11){
                        ToastUtils.showLong("请输入正确的手机号!");
                        return;
                    }
                }

                if (TextUtils.isEmpty(phone)){
                    Toast.makeText(RegisterActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }else if (TextUtils.isEmpty(code)){
                    Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_SHORT).show();
                }else  if (TextUtils.isEmpty(code2)){
                    Toast.makeText(RegisterActivity.this, "请输入邀请码", Toast.LENGTH_SHORT).show();
                }else  if (TextUtils.isEmpty(password)){
                    Toast.makeText(RegisterActivity.this, "请设置密码（6位或以上）", Toast.LENGTH_SHORT).show();
                } else {
                    SendRegister(phone,password,code2,code,"1");
                }
                break;
            default:
                break;
        }
    }



    private void Have_No_Code() {
        Map<String, Object> map = new HashMap<>();
        map.put("oem_id",Constants.OEM_ID);
        OkGo.<String>post(Constants.RECOMMAND_CODE)
                .params("oem_id",Constants.OEM_ID)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        NoCodeBean noCodeBean = gson.fromJson(response.body(), NoCodeBean.class);

                        if (noCodeBean.getCode() >= 0) {

                            //没有邀请码
                            BaseDialog baseDialog = new BaseDialog(RegisterActivity.this,R.layout.dialog_no_code);
                            baseDialog.show();
                            ImageView imageView = baseDialog.findViewById(R.id.iv_close);
                            imageView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    baseDialog.dismiss();
                                }
                            });



                            RecyclerView rv_1 = baseDialog.findViewById(R.id.rv_1);
                            rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
                            RegisterDialogAdapter registerDialogAdapter = new RegisterDialogAdapter(R.layout.item_register, noCodeBean.getResult().getOfficial_user_list());
                            rv_1.setAdapter(registerDialogAdapter);
                            registerDialogAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                    et_code2.setText(registerDialogAdapter.getData().get(position).getRecommand_code());
                                    baseDialog.dismiss();
                                }
                            });



                        } else {
                            Toast.makeText(RegisterActivity.this, noCodeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }



    private void SendCode(String phone,int type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", phone);
        map.put("type", type);

        OkGo.<String>post(Constants.SendMSG)
                .params("user_phone", phone)
                .params("type", type)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        CodeBean codeBean = gson.fromJson(response.body(), CodeBean.class);

                        if (codeBean.getCode() >= 0) {

                            if (timeCount == null) {
                                timeCount = new TimeCount(60 * 1000, 1000);//5s的一个定时器 间隔是1s
                                timeCount.start();

                            }

                            Toast.makeText(RegisterActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(RegisterActivity.this, codeBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }

    private void SendRegister(String user_phone,String user_pwd,String recommand_code,String verify_code,String app_type) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_phone", user_phone);
        map.put("user_pwd", user_pwd);
        map.put("recommand_code", recommand_code);
        map.put("verify_code", verify_code);
        map.put("app_type", app_type);
        map.put("open_id", open_id);
        map.put("user_nick_name", user_nick_name);
        map.put("user_head_img", user_head_img);

        OkGo.<String>post(Constants.REGISTER)
                .params("user_phone", user_phone)
                .params("user_pwd", user_pwd)
                .params("recommand_code", recommand_code)
                .params("verify_code", verify_code)
                .params("app_type", app_type)
                .params("open_id", open_id)
                .params("user_nick_name", user_nick_name)
                .params("user_head_img", user_head_img)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        setData(response);
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        RegisterBean registerBean = gson.fromJson(response.body(), RegisterBean.class);

                        if (registerBean.getCode() >= 0) {
                            //保存登录账号的信息的实体类到本地数据库
                            Realm realm = Realm.getDefaultInstance();
                            AccountBean accountBean = new AccountBean();
                            accountBean.setName(registerBean.getResult().getUser_name());
                            accountBean.setPhone(registerBean.getResult().getUser_phone());
                            accountBean.setPassword(user_pwd);
                            accountBean.setApp_user_id(registerBean.getResult().getUser_id());
                            accountBean.setUser_head_image(registerBean.getResult().getUser_head_img());
                            realm.executeTransaction(new Realm.Transaction() {
                                @Override
                                public void execute(Realm realm) {
                                    realm.copyToRealmOrUpdate(accountBean);
                                    //进入主界面
                                    SPUtils.saveAppUserId(RegisterActivity.this,registerBean.getResult().getUser_id());

                                    SPUtils.saveUserPhone(RegisterActivity.this,registerBean.getResult().getUser_phone());


                                    appManager.killActivity(LoginActivity.class);
                                    startActivity(new Intent(RegisterActivity.this,MainUIActivity.class));
                                    finish();
                                }
                            });


                        } else {
                            Toast.makeText(RegisterActivity.this, registerBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }

                });


    }


    @Override
    protected void onDestroy(){
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.onDestroy();
    }




}
